import cv2
import numpy as np


# 将传入的图片对比
def screenshot_contrast(screenshot, threshold, img):
    # 将目标图片转换为灰度图
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    screenshot_gray = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY)

    # 使用模板匹配查找目标图片在屏幕截图中的位置  274  133
    res = cv2.matchTemplate(screenshot_gray, img_gray, cv2.TM_CCOEFF_NORMED)
    # 设置一个阈值，可以根据需要调整
    # 判断是否达到阈值
    loc = np.where(res >= threshold)
    # 如果找到匹配区域，返回左上角坐标
    if len(loc[0]) > 0:
        pt = (loc[1][0], loc[0][0])
        width, height = img.shape[1], img.shape[0]
        print(pt[0], pt[1], width, height)
        result = pt[0], pt[1], width, height
        return result
    else:
        return None


# 区域图片对比   提高精度
def area_contrast(screenshot, threshold, area_points, img):
    img = read_img(img)
    x, y, w, h = area_points
    cropped_img = screenshot[y:y + h, x:x + w]
    res = screenshot_contrast(cropped_img, threshold, img)
    if res is None:
        return None
    else:
        result = res[0] + area_points[0], res[1] + area_points[1], res[2], res[3]

    return result


# 读取图片
def read_img(img_path):
    img = cv2.imread(img_path, cv2.IMREAD_COLOR)
    if img is None:
        return print("目标路径不存在图片", img_path)

    print('加载目标图片')

    return img
